<!--
 * @Author: panghu chenjh@datamargin.com
 * @Date: 2024-04-10 16:46:15
 * @LastEditors: panghu chenjh@datamargin.com
 * @LastEditTime: 2024-04-12 15:24:58
 * @FilePath: \zheye\src\components\ValidateForm.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <form class="validate-form-container">
    <slot name="default"></slot>
    <div class="submit-area" @click.prevent="submitForm">
      <slot name="submit">
        <button type="submit" class="btn btn-primary">提交</button>
      </slot>
    </div>
  </form>
</template>

<script lang="ts">
import { defineComponent, onUnmounted, ref } from 'vue'
import mitt from 'mitt'
type ValidateFunc = () => boolean
type Emits<EventType extends string | symbol, T> = {
  on(type: EventType, handler: (arg: T) => void): void
  off(type: EventType, handler: (arg: T) => void): void
  emit(type: EventType, arg: T): void
}
type Events = {
  foo: string;
  bar?: number
}
type Emitter = Emits<'form-item-created', ValidateFunc>
type ValidatorFn = () => boolean
export const emitter: Emitter = mitt<Events>()
export default defineComponent({
  emits: ['form-submit'],
  setup (props, context) {
    let funArr: ValidatorFn[] = []
    const submitForm = () => {
      const result = funArr.map(fn => fn()).every(res => res)
      context.emit('form-submit', result)
    }
    const callback = (fn: ValidatorFn): void => {
      funArr.push(fn)
    }
    emitter.on('form-item-created', callback)
    onUnmounted(() => {
      emitter.off('form-item-created', callback)
      funArr = []
    })
    return {
      submitForm
    }
  }
})
</script>

<style scoped>

</style>
